const StringUtil = require('./StringUtil')
const crypto = require('crypto')
const request = require('request')
const config = require('../../config/config')
const secret = 'asklhndkaasldfjl2'

/**
 *
 * 此util主要存放与加解密相关代码
 *
 *
 */

//Token构造函数
function Token(user_id, sign_token, expire_time) {
    this.user_id = user_id
    this.sign_token = sign_token
    this.expire_time = expire_time
}

//获取加密Token
function getEncryptAccessToken(user_id) {
    let token = new Token(user_id, StringUtil.getRandChar(10), Date.now() + 1000 * 60 * 60 * 2)
    const cipher = crypto.createCipher('aes192', secret);
    let crypted = cipher.update(JSON.stringify(token), 'utf8', 'hex');
    crypted += cipher.final('hex');
    return crypted
}

//解密Token
function getDecryptAccessToken(token) {
    const decipher = crypto.createDecipher('aes192', secret);
    let decrypted = decipher.update(token, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}


// 获取微信通用access_token
function getWeChatAccessToken() {
    return new Promise((resolve, reject) => {
        request({
            url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.wechat_config.appID}&secret=${config.wechat_config.appSecret}`,
            method: "GET"
        }, (err, response, body) => {
            if (err)
                return reject(err)
            return resolve(body)
        })

    })
}

//微信小程序签名
function WXBizDataCrypt(appId, sessionKey) {
    this.appId = appId
    this.sessionKey = sessionKey
}

//解密微信小程序openid程序openid
WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
    // base64 decode
    const tempsessionkey = this.sessionKey
    const tempencryptedData = encryptedData
    const tempiv = iv
    const sessionKey = new Buffer(tempsessionkey, 'base64')
    encryptedData = new Buffer(encryptedData, 'base64')
    iv = new Buffer(iv, 'base64')
    try {
        // 解密
        const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
        // 设置自动 padding 为 true，删除填充补位
        decipher.setAutoPadding(true)
        var decoded = ''
        decoded += decipher.update(encryptedData, 'binary', 'utf8')
        decoded += decipher.final('utf8')
        decoded = JSON.parse(decoded)
    } catch (err) {
        throw new Error('Illegal Buffer1')
    }
    if (decoded.watermark.appid !== this.appId) {
        throw new Error('Illegal Buffer2')
    }
    return decoded
}

module.exports.getEncryptAccessToken = getEncryptAccessToken
module.exports.getDecryptAccessToken = getDecryptAccessToken
module.exports.WXBizDataCrypt = WXBizDataCrypt
module.exports.getWeChatAccessToken = getWeChatAccessToken

